package com.authine.cloudpivot.ext.service;

import cn.hutool.core.map.MapBuilder;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.facade.BizObjectFacade;
import com.authine.cloudpivot.engine.api.facade.BizWorkitemFacade;
import com.authine.cloudpivot.engine.api.facade.BizWorkitemFinishedFacade;
import com.authine.cloudpivot.engine.api.model.dto.SimpleWorkDTO;
import com.authine.cloudpivot.engine.api.model.im.WorkRecordModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.domain.runtime.BizWorkflowInstance;
import com.authine.cloudpivot.engine.domain.runtime.BizWorkitem;
import com.authine.cloudpivot.engine.enums.status.WorkRecordStatus;
import com.authine.cloudpivot.engine.enums.type.CorpRelatedType;
import com.authine.cloudpivot.engine.spi.service.IWorkService;
import com.authine.cloudpivot.ext.service.impl.OaWorkItemServiceImpl;
import com.authine.cloudpivot.ext.util.ItemTypeUtils;
import com.authine.cloudpivot.web.api.handler.CustomizedOrigin;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.UUID;

@Service("DingTalkWorkServiceImpl")
@Slf4j
@CustomizedOrigin(level = 1)
public class IWorkOaService implements IWorkService {


    @Autowired
    OaWorkItemServiceImpl oaWorkItemService;
    @Autowired
    BizWorkitemFacade bizWorkitemFacade;
    @Autowired
    BizWorkitemFinishedFacade bizWorkitemFinishedFacade;
    @Autowired
    BizObjectFacade bizObjectFacade;

    @Autowired
    OaToFacade oaToFacade;

    @Override
    public String createWork(SimpleWorkDTO workDTO) {

        log.info("\n===================IWorkOaService.createWork.创建任务:workDTO={}\n", JSON.toJSONString(workDTO));

        //向oa发送待办任务逻辑

        WorkItemModel item = bizWorkitemFacade.get(workDTO.getBizTaskId());

        if (item == null) {
            log.info("发送待办失败,待办任务不存在,item.id={}",workDTO.getBizTaskId());
            return null;
        }
        String oaAppName = oaToFacade.getOaAppName(item.getAppCode());
        if (oaAppName == null){
            log.info("{}应用不在配置中,不用推送",item.getAppCode());
            return null;
        }
        boolean b = oaWorkItemService.sendTodo(item, oaAppName);
        if (b) {
            return "1";
        }
        return  null;
    }

    @Override
    public boolean updateStatus(String bizTaskId, String state) {
        //消待办， 完成,撤销,或删除
        log.info("\n===================IWorkOaService.updateStatus.修改状态:bizTaskId={},state={}\n", bizTaskId,state);

        try {
            return oaWorkItemService.setTodoDone(bizTaskId);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            try {
                WorkItemModel item = bizWorkitemFinishedFacade.get(bizTaskId);

                saveLog(item, ItemTypeUtils.yb,e.getMessage());
            } catch (Exception exception) {
                log.error(e.getMessage(),e);
            }
            return  false;
        }

    }

    @Override
    public boolean updateFlowStatus(String bizFlowId, String bizTaskId, String state) {
        //修改流程状态
        return true;
    }

    @Override
    public boolean removeWork(WorkRecordModel workRecord) {
        //消待办，删除
        log.info("\n===================IWorkOaService.removeWork.删除任务:workRecord={}\n", JSON.toJSONString(workRecord));



        try {
            return oaWorkItemService.deleteToDo(workRecord.getWorkitemId());
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            //向oa发送待办任务逻辑

            try {
                WorkItemModel item = bizWorkitemFinishedFacade.get(workRecord.getWorkitemId());
                saveLog(item, ItemTypeUtils.yb,e.getMessage());
            } catch (Exception exception) {
                log.error(e.getMessage(),e);
            }
            return  false;
        }
    }

    @Override
    public String pushWorkMsg(WorkRecordModel workRecord) {
        log.info("\n===================IWorkOaService.pushWorkMsg.发送消息通知:workRecord={}\n", JSON.toJSONString(workRecord));
        JSONObject bizParams = JSONObject.parseObject(workRecord.getBizParams());

        String workitemId = bizParams.getString("workitemId");
        SimpleWorkDTO workDTO = (new SimpleWorkDTO()).setContent(workRecord.getContent()).setTitle(workRecord.getTitle()).setBizTaskId(workitemId);

        String rst = null;
        String errmsg = "";
        try {
            rst = this.createWork(workDTO);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            errmsg = e.getMessage();
        }
        // 推送成功
        if (StringUtils.isNotEmpty(rst)){
            //推送成功, 生成 recordId , 没有recordId 的日志不会走 消待办操作
            workRecord.setRecordId( UUID.randomUUID().toString().replaceAll("-", ""));
            workRecord.setWorkRecordStatus(WorkRecordStatus.FINISHED);
        }else {
            //推送失败
            workRecord.setWorkRecordStatus(WorkRecordStatus.UNSEND);
            workRecord.setFailRetry(true);
            workRecord.setFailUserRetry(true);
            Integer tryTimes = workRecord.getTryTimes();
            if (tryTimes != null && tryTimes>2){
                WorkItemModel item = bizWorkitemFacade.get(workRecord.getWorkitemId());
                saveLog(item, ItemTypeUtils.db,errmsg);
            }
        }
        return workRecord.getRecordId();
    }

    // 记录推送失败日志
    private void saveLog(WorkItemModel item, String itemType, String msg){

        MapBuilder<String, Object> bizMap = MapBuilder.create(new HashMap<String, Object>());

        bizMap.put("instName",item.getWorkflowCode())
                .put("instModelName",item.getInstanceName())
                .put("approval",item.getParticipantName())
                .put("instId",item.getInstanceId())
                .put("itemId",item.getId())
                .put("rst","失败")
                .put("msg",msg)
                .put("itemType",itemType) ;

        BizObjectCreatedModel bizObject = new BizObjectCreatedModel("oaTodoOpt", bizMap.build(), false);

        String s = bizObjectFacade.saveBizObject(item.getParticipant(), bizObject, false);

    }

    @Override
    public String initChannel() {
        return CorpRelatedType.DINGTALK.toString();
    }


    
}
